#!/bin/bash

# shellcheck source=meta-facebook/recipes-fb/obmc_functions/files/fb-common-functions
source /usr/libexec/fb-common-functions

check_valid_sgpio() {
    sgpio_vaild0=$(gpioget 2 146)
    sgpio_vaild1=$(gpioget 2 198)
    sgpio_vaild2=$(gpioget 2 18)

    if [[ "$sgpio_vaild0" == "0" && "$sgpio_vaild1" == "0" && "$sgpio_vaild2" == "1" ]]; then
        return 0  # true
    else
        return 1  # false
    fi
}

# Power Good Status
power_status() {
    check_valid_sgpio
    valid_sgpio=$?

    if [ "$(get_gpio "host0-ready")" -eq 1 ] && [ "$valid_sgpio" -eq 0 ] ; then
        echo "on"
    else
        echo "off"
    fi
}

# Force DC off
force_power_off() {
    if [ "$(power_status)" == "on" ]; then
        set_gpio power-host-control 0
        sleep 6
        set_gpio power-host-control 1
        sleep 6
    fi

    # Workaround for AMD force shutdown failure.
    if [ "$(power_status)" == "on" ]; then
        set_gpio reset-control 0
        sleep 1
        set_gpio reset-control 1
        sleep 3

        set_gpio power-host-control 0
        sleep 1
        set_gpio power-host-control 1
        sleep 1

        for i in $(seq 1 10)
        do
            sleep 1
            if [ "$(power_status)" == "off" ]; then
               return 0
            fi

            if [ "$i" -eq 10 ]; then
               return 1
            fi
        done
    fi
}

# Graceful DC off
graceful_power_off() {
    if [ "$(power_status)" == "on" ]; then
        set_gpio power-host-control 0
        sleep 1
        set_gpio power-host-control 1
        sleep 1

        # wait host power off
        for i in $(seq 1 20)
        do
            sleep 1
            if [ "$(power_status)" == "off" ]; then
               break
            fi
        done
    fi
}

# DC on
power_on() {
    if [ "$(power_status)" == "off" ]; then
        set_gpio power-host-control 0
        sleep 1
        set_gpio power-host-control 1
        sleep 1

        for i in $(seq 1 10)
        do
            sleep 1
            if [ "$(power_status)" == "on" ]; then
               return 0
            fi

            if [ "$i" -eq 10 ]; then
               return 1
            fi
        done
    fi
    return 0
}

# Host reset
power_reset() {
    set_gpio reset-control 0
    sleep 1
    set_gpio reset-control 1
    sleep 1
    return 0
}
